const { exec } = require("child_process");
const path = require("path");

// 路径和文件名需要根据你的实际情况进行更改
// const baseImage = 'image/KV_RED_CMYK.tif';
const baseImage = "image/DX_4247EQA_CMYK.tif";
const offset = 0.5;
const dpi = 300;
const externalIcc = "image/JapanColor2001Coated.icc";

const overlays = [
  {
    image: "image/MB_star_1C.svg",
    width: 500 * offset,
    x: ((14338 - 1000) / 2) * offset,
    y: 1000 * offset,
  },
  {
    image: "image/text_w.svg",
    width: 3000 * offset,
    x: (1000 + 3000) * offset,
    y: 3000 * offset,
  },
  {
    image: "image/text_b.svg",
    width: 3000 * offset,
    x: (1000 + 14338 / 2) * offset,
    y: 3000 * offset,
  },
  // {
  //   image: "image/online_text.svg",
  //   width: 3000 * offset,
  //   x: (1000 + 14338 / 2) * offset,
  //   y: 4000 * offset,
  // },
];
const outputImage = "image/result.tif";

const executeCommand = (command, output) => {
  return new Promise((resolve, reject) => {
    exec(command, (error, stdout, stderr) => {
      console.log(command);
      console.log(output);
      if (error) {
        reject({ command, message: `执行出错: ${error}` });
        return;
      }
      if (stderr) {
        reject({ command, message: `错误信息: ${stderr}` });
        return;
      }
      resolve({ command, message: `stdout: ${stdout}`, output });
    });
  });
};

// handle svg to tif, with dpi and icc
const svg2tif = (image, width) => {
  const command = `vips thumbnail ${image} ${image}.tif --size both ${width}`;
  console.log("svg2tif: ", command);
  return executeCommand(command, `${image}.tif`);
  // todo 把overlay转换成cmyk，中间文件使用The VIPS file format
  // return new Promise((resolve, reject) => {
  // executeCommand(command, `${image}.tif`)
  // .then((res) => {
  //   const { output } = res
  //   const [pathAndName, ext] = output.split('.')
  //   const cmykOutput = `${pathAndName}_cmyk.tif`
  //   // 把overlay转换成cmyk
  //   const cmykCommand = `vips colourspace ${output} ${cmykOutput} cmyk`
  //   executeCommand(cmykCommand, cmykOutput)
  //   .then((res) => {
  //     const { output } = res
  //     const [pathAndName, ext] = output.split('.')
  //     const dpiOutput = `${pathAndName}_dpi.tif`
  //     const resMm = dpi / 2.54 / 10
  //     // 设置dpi
  //     const dpiCommand = `vips tiffsave ${output} ${dpiOutput} --resunit cm --xres ${resMm} --yres ${resMm} --Q=100 --pyramid=true --bigtiff=true --depth=onepixel`
  //     executeCommand(dpiCommand, dpiOutput)
  //     .then((res) => {
  //       const { output } = res
  //       const [pathAndName, ext] = output.split('.')
  //       const iccOutput = `${pathAndName}_icc.tif`
  //       // 设置icc
  //       const iccCommand = `vips icc_transform ${output} ${iccOutput} ${externalIcc}`
  //       executeCommand(iccCommand, iccOutput)
  //       .then((res) => {
  //         resolve(res)
  //       })
  //       .catch((err) => {
  //         reject(err)
  //       })
  //     })
  //     .catch((err) => {
  //       reject(err)
  //     })
  //   })
  //   .catch((err) => {
  //     reject(err)
  //   })
  // })
  // .catch((err) => {
  //   reject(err)
  // })
  // })
};

let cliMode = "";
let cliX = "";
let cliY = "";
const overlayTiffPromises = [];
overlays.forEach((item) => {
  const { image, width, mode = 2, x, y } = item;
  cliMode += `${mode} `;
  cliX += `${parseInt(x)} `;
  cliY += `${parseInt(y)} `;

  overlayTiffPromises.push(svg2tif(image, width));
});

Promise.all(overlayTiffPromises)
  .then((overlayTiffs) => {
    console.log("overlay in tif", overlayTiffs);

    const cliIn = overlayTiffs.reduce((acc, curr) => {
      return acc + (acc ? " " : "") + curr.output;
    }, "");
    console.log(cliIn);

    const compositeCommandOutput = `${outputImage}.vips`;
    const compositeCommand = `vips composite "${baseImage} ${cliIn}" ${compositeCommandOutput} "${cliMode}" --x "${cliX}" --y "${cliY}" --compositing-space cmyk`;
    console.log("command: ", compositeCommand);

    executeCommand(compositeCommand, compositeCommandOutput)
      .then((res) => {
        const { output } = res;
        const command = `vips tiffsave ${output} ${outputImage}f --Q=100 --pyramid=true --resunit=cm --xres=11.811 --yres=11.811 --bigtiff=true --depth=onepixel --keep=icc`;
        executeCommand(command, outputImage);
      })
      .catch((err) => {
        console.error(JSON.parse(err));
      });
  })
  .catch((err) => {
    console.error(JSON.parse(err));
  });
